<template>
    <div class="setUserInfo">
        <div class="top">
            <van-icon name="arrow-left" @click="$router.back()" />
            <p>设置个人信息</p>
        </div>
        <div class="form">
            <van-field name="uploader" label="设置头像:">
                <template #input>
                    <van-uploader v-model="value" multiple :max-count="1" :after-read="afterRead"
                        :before-delete="beforeDelete" />
                </template>
            </van-field>
        </div>
    </div>
</template>

<style lang="less" scoped>
.setUserInfo {
    padding: 10px;

    .top {
        position: relative;

        i {
            font-weight: bold;
            position: absolute;
            font-size: 33px;
        }

        p {
            text-align: center;
            font-size: 23px;
            font-weight: bold;
        }
    }

    .content {
        van-uploader {
            height: 100px;
            width: 100px;
        }
    }
}
</style>

<script lang="ts" setup>
import { ref } from 'vue';
import api from '../api/request'
import http from '../api/index'
import { showConfirmDialog } from 'vant';


// 头像
const value = ref([
    { url: '', },
]);
// 图片上传路径
let dirName = 'images'

// 获取用户信息
let token: any = localStorage.getItem('token');

api.userInfo({ token })
    .then(res => {
        // 用户头像
        value.value[0].url = http.host + res.rows.imgUrl;
    })

// 删除头像
const beforeDelete: any = (file: any, index: number) => {
    return new Promise((resolve, reject) => {
        showConfirmDialog({
            title: '提示',
            message:'是否删除头像',
        })
            .then(() => {
                // 重置用户头像
                let imgUrl = '/static/images/abc.jpg';
                let picUrl =file.url;
                // file.url.split(`${http.host}`).join("")
                // 删除图片
                 // 重新设置用户头像
                 api.setImg({ token, imgUrl})
                api.deleteImg({ picUrl,dirName })
                resolve(true);
            })
            .catch(() => {
                reject();
            });
    })
}

// 上传头像
const afterRead = (file: any) => {
    let fd = new FormData()
    fd.append('photo', file.file)
    api.uploadUserImg(fd)
        .then(res => {
            res.picUrl = res.picUrl.slice(0, -1);
            value.value[0].url = res.picUrl;
            // 设置用户头像
            api.setImg({ token, imgUrl: res.picUrl})
        })
}



</script>